import { Location } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { UntypedFormGroup, Validators, UntypedFormBuilder } from '@angular/forms';
import { AfMessageService, AfSecurityService } from '@core';
import { SettingsService } from '@delon/theme';
import { NzModalService } from 'ng-zorro-antd/modal';

import { SecurityService } from '../security.service';

@Component({
  selector: 'app-password',
  templateUrl: './password.component.html',
  styleUrls: ['./password.component.less']
})
export class PasswordComponent implements OnInit {
  isVisible = false;
  user: any;
  constructor(
    private fb: UntypedFormBuilder,
    private settingSrv: SettingsService,
    private securitySrv: SecurityService,
    private msgSrv: AfMessageService,
    private loca: Location,
    private modal: NzModalService
  ) {
    this.user = this.settingSrv.getUser();
    // console.log('this.user.id', this.user.id);
  }

  form!: UntypedFormGroup;
  submitting = false;

  ngOnInit(): void {
    this.form = this.fb.group({
      username: [this.user.id, []],
      oldPassword: ['', [Validators.required]],
      password1: ['', [Validators.required]],
      password2: ['', [Validators.required]]
    });
  }

  submit(): void {
    this.modal.confirm({
      nzTitle: '<i>是否要修改密码?</i>',
      nzContent: '<b>确认修改密码，请点击确认按钮</b>',
      nzOnOk: () => {
        this.form.controls['username'].setValue(this.user.id);
        const body = this.form.getRawValue();
        this.submitting = true;
        this.securitySrv.updateUserPassword(body).subscribe(res => {
          if (res.status) {
            this.msgSrv.msg_success(`密码修改成功`);
          } else {
            this.msgSrv.msg_warning(`${res.msg}`);
          }
        });

        setTimeout(() => {
          this.submitting = false;
        }, 1000);
      }
    });
  }

  back() {
    this.loca.back();
  }
}
